package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.RequestObject.LeanPaintReportTempObject;
import com.ugoodtech.mdcc.client.controller.RequestObject.PaintReportObject;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.StationLeanPaintReportService;
import com.ugoodtech.mdcc.client.service.UserLogService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.StationLeanPaintSatisfactionReport.OperationalDataAnalysis;
import com.ugoodtech.mdcc.core.domain.StationLeanPaintSatisfactionReport.OperationalDataAnalysisTemp;
import com.ugoodtech.mdcc.core.domain.StationLeanPaintSatisfactionReport.QOperationalDataAnalysis;
import com.ugoodtech.mdcc.core.domain.StationLeanPaintSatisfactionReport.QOperationalDataAnalysisTemp;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.utils.AnswerOtherUtil;
import com.ugoodtech.mdcc.core.utils.ArrayStringUtil;
import com.ugoodtech.mdcc.core.utils.DateUtil;
import com.ugoodtech.mdcc.core.utils.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "精益钣金报告相关接口")
@RestController
@RequestMapping("/stationLeanPaintReport")
public class StationLeanPaintReportController {

    private final static Logger logger = LoggerFactory.getLogger(StationLeanPaintReportController.class);

    @Autowired
    private StationLeanPaintReportService stationLeanPaintReportService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationPaintReportRepository stationPaintReportRepository;

    @Autowired
    private StationLeanPaintReportTempRepository stationLeanPaintReportTempRepository;

    @Autowired
    private StationReportUnFinshedRepository stationReportUnFinshedRepository;

    @Autowired
    private OperationalDataAnalysisRepository operationalDataAnalysisRepository;

    @Autowired
    private OperationalDataAnalysisTempRepository operationalDataAnalysisTempRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @ApiOperation("创建精益板喷报告-改")
    @RequestMapping(value = "createReport", method = RequestMethod.POST)
    public JsonResponse createReport(@ApiIgnore Principal principal,
                                     @RequestBody PaintReportObject stationPaintReports,
                                     @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId,
                                     @ApiParam("报告状态") @RequestParam(value = "reportType") String reportType,
                                     @ApiParam("暂存的报告ID") @RequestParam(value = "saveReportId", required = false) Long saveReportId,
                                     @ApiParam("报告ID") @RequestParam(value = "reportId", required = false) Long reportId) {
        logger.info("***************************************************************");
        logger.info("<<<<<<<<<<<<<<<<<<创建精益钣喷报告>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<维修站ID为：" + stationId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<暂存报告ID为" + saveReportId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<重新提交的报告ID为：" + reportId + ">>>>>>>>>>>>>>>>>");
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        try {
            List<StationPaintReport> regularServiceReports = stationPaintReports.getStationPaintReports();
            logger.info("<<<<<<<<<<<<<<<<<<提交的题目数量为：" + regularServiceReports.size() + ">>>>>>>>>>>>>>>>>");
            List<OperationalDataAnalysis> operationalDataObjects = stationPaintReports.getOperationalDataAnalysisList();
            if (operationalDataObjects.size() != 7) {
                return JsonResponse.errorResponseWithError("抱歉", "改善月数据有异常，请检查");
            }
            logger.info("<<<<<<<<<<<<<<<<<<提交的表格数量为：" + operationalDataObjects.size() + ">>>>>>>>>>>>>>>>>");
            JsonResponse jsonResponse = toComplete(clientUser, regularServiceReports, operationalDataObjects, stationId, reportType, saveReportId, reportId);
//            if(jsonResponse.isSuccess()){
//                //新增日志================================
//                userLogService.addUserLog(clientUser,stationId, LogConstants.operate_type_add,LogConstants.business_type_lean_paint_report,null,null);
//            }
            return jsonResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "创建失败");
        }
    }

    private JsonResponse toComplete(User user, List<StationPaintReport> stationPaintReports,
                                    List<OperationalDataAnalysis> operationalDataObjects,
                                    Long stationId, String reportType, Long saveReportId, Long reportId) {
        if (operationalDataObjects == null || operationalDataObjects.size() == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "请将题目全部完成");
        }
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "维修站未找到");
        }
        if (StringUtils.isEmpty(reportType)) {
            return JsonResponse.errorResponseWithError("抱歉", "报告状态错误");
        }

        //判断是否有暂存的报告 有的话 先删除暂存的报告
        if (saveReportId != null && saveReportId != 0) {
            logger.info("<<<<<<<<<<<<<<<<<<有暂存的精益板喷报告>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<暂存报告id为" + saveReportId + ">>>>>>>>>>>>>>>>>");
            QStationReportTemp qStationReportTemp = QStationReportTemp.stationReportTemp;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReportTemp.deleted.eq(false));
            builder.and(qStationReportTemp.enabled.eq(true));
            builder.and(qStationReportTemp.reportCategory.eq(Constants.PAINT_REPORT));
            builder.and(qStationReportTemp.id.eq(saveReportId));
            StationReportTemp stationReportUnFinshed = stationReportUnFinshedRepository.findOne(builder);
            if (stationReportUnFinshed == null) {
                return JsonResponse.errorResponseWithError("抱歉", "暂存的报告未找到");
            }
            QStationLeanPaintReportTemp qStationLeanPaintReportTemp = QStationLeanPaintReportTemp.stationLeanPaintReportTemp;
            builder = new BooleanBuilder();
            builder.and(qStationLeanPaintReportTemp.deleted.eq(false));
            builder.and(qStationLeanPaintReportTemp.enabled.eq(true));
            builder.and(qStationLeanPaintReportTemp.stationReportUnFinshed.id.eq(saveReportId));
            List<StationLeanPaintReportTemp> unFinshedList = (List<StationLeanPaintReportTemp>) stationLeanPaintReportTempRepository.findAll(builder);
            if (unFinshedList.size() <= 0) {
                return JsonResponse.errorResponseWithError("抱歉", "暂存的报告答案结果未找到");
            }
            logger.info("<<<<<<<<<<<<<<<<<<逻辑删除暂存精益钣喷报告>>>>>>>>>>>>>>>>>");
            stationReportUnFinshed.setDeleted(true);
            stationReportUnFinshed.setEnabled(false);
            stationReportUnFinshedRepository.save(stationReportUnFinshed);
            logger.info("<<<<<<<<<<<<<<<<<<逻辑删除暂存精益钣喷报告的答案>>>>>>>>>>>>>>>>>");
            for (StationLeanPaintReportTemp unFinshed : unFinshedList) {
                unFinshed.setDeleted(true);
                unFinshed.setEnabled(false);
                stationLeanPaintReportTempRepository.save(unFinshed);
            }
        }

        //第一次新建
        if (reportId == null) {
            logger.info("<<<<<<<<<<<<<<<<<<设置维修站，说明此维修站填写过精益钣喷>>>>>>>>>>>>>>>>>");
            station.setIsPaint(1);
            stationRepository.save(station);
            logger.info("<<<<<<<<<<<<<<<<<<第一次创建精益钣喷报告>>>>>>>>>>>>>>>>>");
            StationReport stationReport = new StationReport();
            stationReport.setStation(station);
            stationReport.setUser(user);
            stationReport.setReportType(reportType);
            stationReport.setCategory(Constants.PAINT_REPORT);
            stationReport = stationReportRepository.save(stationReport);
            for (StationPaintReport stationPaintReport : stationPaintReports) {
                stationPaintReport.setStationReport(stationReport);
                stationPaintReportRepository.save(stationPaintReport);
            }
            for (OperationalDataAnalysis operationalData : operationalDataObjects) {
                logger.info("<<<<<<<<<<<<<<<<<<indexId为：" + operationalData.getIndexId() + ">>>>>>>>>>>>>>>>>");
                operationalData.setId(null);
                operationalData.setReportId(stationReport.getId());
                operationalData.setStationId(stationId);
                operationalDataAnalysisRepository.save(operationalData);
            }
            logger.info("<<<<<<<<<<<<<<<<<<开始计算表格中的数据>>>>>>>>>>>>>>>>>");
            JsonResponse jsonResponse = stationLeanPaintReportService.calculateKpiData(stationReport.getId(), stationId);
            if (jsonResponse.isSuccess()) {
                String stationNum = "";
                if (null != station) {
                    stationNum = station.getStationNum();
                }
                userLogService.addUserLog(user, stationNum, stationReport.getId(), Constants.PAINT_REPORT, LogConstants.operate_type_add, LogConstants.business_type_lean_paint_report, null, null);
            }
            return jsonResponse;
        } else {
            logger.info("<<<<<<<<<<<<<<<<<<开始更新精益钣喷报告>>>>>>>>>>>>>>>>>");
            QStationPaintReport qStationPaintReport = QStationPaintReport.stationPaintReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationPaintReport.deleted.eq(false));
            builder.and(qStationPaintReport.enabled.eq(true));
            builder.and(qStationPaintReport.stationReport.id.eq(reportId));
            List<StationPaintReport> stationLeanPaintReportList = (List<StationPaintReport>) stationPaintReportRepository.findAll(builder);
            StationReport stationReport = stationReportRepository.findOne(reportId);
            logger.info("<<<<<<<<<<<<<<<<<<更新报告答案>>>>>>>>>>>>>>>>>");
            //                todo=====
            String desc = "";
            for (StationPaintReport unFinished : stationPaintReports) {
                Question question = questionRepository.findOne(unFinished.getQuestionId());
                for (StationPaintReport complete : stationLeanPaintReportList) {
                    if (unFinished.getQuestionId().equals(complete.getQuestionId())) {
                        //                        如果题目的答案有修改的话记录日志===============================================
                        if (!filterAnswerId(complete.getAnswerOther()).equals(unFinished.getAnswerOther()) ||
                                !filterAnswerId(complete.getAnswerId()).equals(unFinished.getAnswerId())) {
                            desc += question.getSubject() + ":";
                            desc += getAnswerString(complete.getAnswerId()) + filterAnswerOther(complete.getAnswerOther()) + "-->>" + getAnswerString(unFinished.getAnswerId()) + filterAnswerOther(unFinished.getAnswerOther()) + ",";
                        }
//                        =========================================================================
                        complete.setAnswerOther(unFinished.getAnswerOther());
                        complete.setAnswerId(unFinished.getAnswerId());
                        complete.setAnswerPhoto(unFinished.getAnswerPhoto());
                        complete.setStationReport(stationReport);
                        stationPaintReportRepository.save(complete);
                    }
                    StationPaintReport paintReport = stationPaintReportRepository.selectAnswerByQuestion(reportId, unFinished.getQuestionId());
                    if (paintReport == null) {
                        unFinished.setStationReport(stationReport);
                        stationPaintReportRepository.save(unFinished);
                    }
                }
            }
            //保存修改者并设置修改时间
            Date date = new Date();
            stationReport.setEditUser(user);
            stationReport.setUpdateTime(date);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
            stationReport.setUpdateTimeStr(simpleDateFormat.format(date));
            stationReport.setEditUser(user);

            Map<String, Object> data = new HashMap<>();
            data.put("str", desc);
            String stationNum = "";
            if (null != station) {
                stationNum = station.getStationNum();
            }
//            如果描述不是空的话====================================================
            if (!StringUtils.isEmpty(desc)) {
                userLogService.addUserLog(user, stationNum, stationReport.getId(), Constants.PAINT_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_lean_paint_report, null, data);
            }

            logger.info("<<<<<<<<<<<<<<<<<<设置维修站，说明此维修站填写过精益钣喷>>>>>>>>>>>>>>>>>");
            station.setIsPaint(1);
            stationRepository.save(station);
            logger.info("<<<<<<<<<<<<<<<<<<更新完毕>>>>>>>>>>>>>>>>>");
            QOperationalDataAnalysis operationalDataAnalysis = QOperationalDataAnalysis.operationalDataAnalysis;
            builder = new BooleanBuilder();
            builder.and(operationalDataAnalysis.deleted.eq(false));
            builder.and(operationalDataAnalysis.enabled.eq(true));
            builder.and(operationalDataAnalysis.reportId.eq(reportId));
            builder.and(operationalDataAnalysis.stationId.eq(stationId));
            List<OperationalDataAnalysis> operationalDataAnalysisList = (List<OperationalDataAnalysis>) operationalDataAnalysisRepository.findAll(builder);
            logger.info("<<<<<<<<<<<<<<<<<<将原来的表格数据>>>>>>>>>>>>>>>>>");
            for (OperationalDataAnalysis unFinished : operationalDataAnalysisList) {
                unFinished.setDeleted(true);
                unFinished.setEnabled(false);
                operationalDataAnalysisRepository.save(unFinished);
            }
            logger.info("<<<<<<<<<<<<<<<<<<新增新的表格数据>>>>>>>>>>>>>>>>>");
            for (OperationalDataAnalysis operationalData : operationalDataObjects) {
                operationalData.setStationId(stationId);
                operationalData.setReportId(reportId);
                operationalDataAnalysisRepository.save(operationalData);
            }
            logger.info("<<<<<<<<<<<<<<<<<<开始计算表格中的数据>>>>>>>>>>>>>>>>>");
            return stationLeanPaintReportService.calculateKpiData(reportId, stationId);
        }
    }

    @ApiOperation("暂时存储精益板喷报告-改")
    @RequestMapping(value = "saveReport", method = RequestMethod.POST)
    public JsonResponse saveReport(@ApiIgnore Principal principal,
                                   @RequestBody LeanPaintReportTempObject stationLeanPaintReportTempList,
                                   @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId,
                                   @ApiParam("unfinished") @RequestParam(value = "reportType") String reportType,
                                   @ApiParam("暂存的报告ID") @RequestParam(value = "tempReportId", required = false) Long reportId,
                                   @ApiParam("当前暂存的章节ID") @RequestParam(value = "sectionId") Long sectionId,
                                   @ApiParam("已经提交过的报告ID") @RequestParam(value = "completeReportId", required = false) Long completeReportId,
                                   @ApiParam("锚点") @RequestParam(value = "anchor") String anchor) {
        logger.info("***************************************************************");
        logger.info("<<<<<<<<<<<<<<<<<<暂存精益钣喷报告>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<维修站ID为：" + stationId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<暂存报告ID为" + reportId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<已经提交过的报告ID：" + completeReportId + ">>>>>>>>>>>>>>>>>");
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        try {
            List<StationLeanPaintReportTemp> stationLeanPaintReportTemps = stationLeanPaintReportTempList.getStationLeanPaintReportTempList();
            logger.info("<<<<<<<<<<<<<<<<<<暂存的题目数量为：" + stationLeanPaintReportTemps.size() + ">>>>>>>>>>>>>>>>>");
            List<OperationalDataAnalysisTemp> operationalDataAnalysisTempList = null;
            if (stationLeanPaintReportTempList.getOperationalDataAnalysisTempList() != null) {
                operationalDataAnalysisTempList = stationLeanPaintReportTempList.getOperationalDataAnalysisTempList();
                if (operationalDataAnalysisTempList.size() != 7) {
                    return JsonResponse.errorResponseWithError("抱歉", "改善月数据有异常，请检查");
                }
                logger.info("<<<<<<<<<<<<<<<<<<暂存的表格数量为：" + operationalDataAnalysisTempList.size() + ">>>>>>>>>>>>>>>>>");
            }
            JsonResponse jsonResponse = toSave(clientUser, stationLeanPaintReportTemps, operationalDataAnalysisTempList, stationId, reportType, reportId, sectionId, anchor, completeReportId);
//            if(jsonResponse.isSuccess()){
//                //暂存日志================================
//                userLogService.addUserLog(clientUser, LogConstants.operate_type,LogConstants.business_type_lean_paint_report,null,null);
//            }
            return jsonResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "创建失败");
        }
    }


    private JsonResponse toSave(User user, List<StationLeanPaintReportTemp> leanPaintReportTemps, List<OperationalDataAnalysisTemp> operationalDataAnalysisTempList,
                                Long stationId, String reportType, Long reportId, Long sectionId, String anchor, Long completeReportId) {
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "维修站未找到");
        }
        if (StringUtils.isEmpty(reportType)) {
            return JsonResponse.errorResponseWithError("抱歉", "报告状态错误");
        }
        StationReportTemp stationReport = null;
        /**
         * 当次报告已经提交过 并且没有暂存报告就执行以下代码块
         */
        if (reportId == null || reportId == 0) {
            if (completeReportId != null && completeReportId != 0) {
                logger.info("<<<<<<<<<<<<<<<<<<报告已经提交过-（提交-暂存）>>>>>>>>>>>>>>>>>");
                logger.info("<<<<<<<<<<<<<<<<<<新建暂存的报告>>>>>>>>>>>>>>>>>");
                stationReport = new StationReportTemp();
                stationReport.setStation(station);
                stationReport.setUser(user);
                stationReport.setReportType(reportType);
                stationReport.setReportCategory(Constants.PAINT_REPORT);
                stationReport.setSectionId(sectionId);
                stationReport.setAnchor(anchor);
                stationReport = stationReportUnFinshedRepository.save(stationReport);
                for (StationLeanPaintReportTemp leanPaintReportTemp : leanPaintReportTemps) {
                    leanPaintReportTemp.setStationReportUnFinshed(stationReport);
                    stationLeanPaintReportTempRepository.save(leanPaintReportTemp);
                }
                //判断 如果7天表格不为NULL 就执行
                if (operationalDataAnalysisTempList != null && operationalDataAnalysisTempList.size() > 0) {
                    logger.info("<<<<<<<<<<<<<<<<<<暂存表格数据>>>>>>>>>>>>>>>>>");
                    for (OperationalDataAnalysisTemp operationalDataAnalysis : operationalDataAnalysisTempList) {
                        logger.info("<<<<<<<<<<<<<<<<<<indexId为：" + operationalDataAnalysis.getIndexId() + ">>>>>>>>>>>>>>>>>");
                        operationalDataAnalysis.setReportId(stationReport.getId());
                        operationalDataAnalysis.setStationId(stationId);
                        operationalDataAnalysisTempRepository.save(operationalDataAnalysis);
                    }
                } else {
                    logger.info("<<<<<<<<<<<<<<<<<<没有传入暂存的改善月表格 将已经提交的数据复制过来>>>>>>>>>>>>>>>>>");
                    //如果没有传入暂存的改善月表格 就将已经提交的数据复制过来
                    QOperationalDataAnalysis qOperationalDataAnalysis = QOperationalDataAnalysis.operationalDataAnalysis;
                    BooleanBuilder builder = new BooleanBuilder();
                    builder.and(qOperationalDataAnalysis.deleted.eq(false));
                    builder.and(qOperationalDataAnalysis.enabled.eq(true));
                    builder.and(qOperationalDataAnalysis.stationId.eq(stationId));
                    builder.and(qOperationalDataAnalysis.reportId.eq(completeReportId));
                    List<OperationalDataAnalysis> operationalDataAnalysisList = (List<OperationalDataAnalysis>) operationalDataAnalysisRepository.findAll(builder);
                    for (OperationalDataAnalysis operationalDataAnalysis : operationalDataAnalysisList) {
                        OperationalDataAnalysisTemp operationalDataAnalysisTemp = new OperationalDataAnalysisTemp();
                        operationalDataAnalysisTemp.setStationId(stationId);
                        operationalDataAnalysisTemp.setReportId(stationReport.getId());
                        operationalDataAnalysisTemp.setIndexId(operationalDataAnalysis.getIndexId());
                        operationalDataAnalysisTemp.setSprayPaintOfMonth(operationalDataAnalysis.getSprayPaintOfMonth());
                        operationalDataAnalysisTemp.setSprayPaintOfNum(operationalDataAnalysis.getSprayPaintOfNum());
                        operationalDataAnalysisTemp.setSprayPaintOfPersonNum(operationalDataAnalysis.getSprayPaintOfPersonNum());
                        operationalDataAnalysisTemp.setPrayPaintOfStationNum(operationalDataAnalysis.getPrayPaintOfStationNum());
                        operationalDataAnalysisTemp.setPrayPaintOfAverage(operationalDataAnalysis.getPrayPaintOfAverage());
                        operationalDataAnalysisTemp.setPaintMoney(operationalDataAnalysis.getPaintMoney());
                        operationalDataAnalysisTemp.setPainterMoneyOfMonth(operationalDataAnalysis.getPainterMoneyOfMonth());
                        operationalDataAnalysisTemp.setBrankStationNum(operationalDataAnalysis.getBrankStationNum());
                        operationalDataAnalysisTemp.setReworkNum(operationalDataAnalysis.getReworkNum());
                        operationalDataAnalysisTempRepository.save(operationalDataAnalysisTemp);
                    }
                }
                QStationPaintReport qStationPaintReport = QStationPaintReport.stationPaintReport;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qStationPaintReport.deleted.eq(false));
                builder.and(qStationPaintReport.enabled.eq(true));
                builder.and(qStationPaintReport.stationReport.id.eq(completeReportId));
                builder.and(qStationPaintReport.stationReport.category.eq(Constants.PAINT_REPORT));
                List<StationPaintReport> stationPaintReports = (List<StationPaintReport>) stationPaintReportRepository.findAll(builder);
                logger.info("<<<<<<<<<<<<<<<<<<开始插入暂存数据>>>>>>>>>>>>>>>>>");
                for (StationPaintReport complete : stationPaintReports) {
                    for (StationLeanPaintReportTemp unfinshed : leanPaintReportTemps) {
                        //判断 如果QuestionID一样结束此次循环
                        if (unfinshed.getQuestionId().equals(complete.getQuestionId())) {
                            continue;
                        }
                        //判断 如果QuestionID加上暂存的报告ID查询出来的对象不存在 就直接新建
                        StationLeanPaintReportTemp leanPaintReportTemp = stationLeanPaintReportTempRepository.selectAnswerByQuestion(stationReport.getId(), complete.getQuestionId());
                        if (leanPaintReportTemp == null) {
                            StationLeanPaintReportTemp temp = new StationLeanPaintReportTemp();
                            temp.setAnswerId(complete.getAnswerId());
                            temp.setAnswerPhoto(complete.getAnswerPhoto());
                            temp.setAnswerOther(complete.getAnswerOther());
                            temp.setQuestionId(complete.getQuestionId());
                            temp.setStationReportUnFinshed(stationReport);
                            stationLeanPaintReportTempRepository.save(temp);
                        }
                    }
                }
                logger.info("<<<<<<<<<<<<<<<<<<暂存成功>>>>>>>>>>>>>>>>>");
                logger.info("<<<<<<<<<<<<<<<<<<返回暂存的ID：" + stationReport.getId() + ">>>>>>>>>>>>>>>>>");
                logger.info("***************************************************************");
                return JsonResponse.successResponseWithData(stationReport.getId());
            }
        }
        /**
         * 首次创建报告并第一次暂存
         */
        if (reportId == null) {
            logger.info("<<<<<<<<<<<<<<<<<<首次创建报告并第一次暂存>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<新建暂存报告>>>>>>>>>>>>>>>>>");
            stationReport = new StationReportTemp();
            stationReport.setStation(station);
            stationReport.setUser(user);
            stationReport.setReportType(reportType);
            stationReport.setReportCategory(Constants.PAINT_REPORT);
            stationReport.setSectionId(sectionId);
            stationReport.setAnchor(anchor);
            stationReport = stationReportUnFinshedRepository.save(stationReport);
            for (StationLeanPaintReportTemp leanPaintReportTemp : leanPaintReportTemps) {
                leanPaintReportTemp.setStationReportUnFinshed(stationReport);
                stationLeanPaintReportTempRepository.save(leanPaintReportTemp);
            }
            if (operationalDataAnalysisTempList != null) {
                logger.info("<<<<<<<<<<<<<<<<<<新暂存建表格数据>>>>>>>>>>>>>>>>>");
                for (OperationalDataAnalysisTemp operationalDataAnalysisTemp : operationalDataAnalysisTempList) {
                    operationalDataAnalysisTemp.setStationId(stationId);
                    operationalDataAnalysisTemp.setReportId(stationReport.getId());
                    operationalDataAnalysisTempRepository.save(operationalDataAnalysisTemp);
                }
            }
            logger.info("<<<<<<<<<<<<<<<<<<新建成功>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<返回暂存的ID：" + stationReport.getId() + ">>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponseWithData(stationReport.getId());
        } else {
            /**
             * 多次暂存
             */
            logger.info("<<<<<<<<<<<<<<<<<<多次暂存报告>>>>>>>>>>>>>>>>>");
            QStationLeanPaintReportTemp qStationLeanPaintReportTemp = QStationLeanPaintReportTemp.stationLeanPaintReportTemp;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationLeanPaintReportTemp.deleted.eq(false));
            builder.and(qStationLeanPaintReportTemp.enabled.eq(true));
            builder.and(qStationLeanPaintReportTemp.stationReportUnFinshed.id.eq(reportId));
            List<StationLeanPaintReportTemp> stationLeanPaintReportTemps = (List<StationLeanPaintReportTemp>) stationLeanPaintReportTempRepository.findAll(builder);
            QStationReportTemp qStationReportTemp = QStationReportTemp.stationReportTemp;
            builder = new BooleanBuilder();
            builder.and(qStationReportTemp.deleted.eq(false));
            builder.and(qStationReportTemp.enabled.eq(true));
            builder.and(qStationReportTemp.id.eq(reportId));
            StationReportTemp saveStationReportTemp = stationReportUnFinshedRepository.findOne(builder);
            logger.info("<<<<<<<<<<<<<<<<<<开始更新暂存报告的答案>>>>>>>>>>>>>>>>>");
            for (StationLeanPaintReportTemp leanPaintReportTemp : leanPaintReportTemps) {

                for (StationLeanPaintReportTemp unfinshed : stationLeanPaintReportTemps) {

                    if (leanPaintReportTemp.getQuestionId().equals(unfinshed.getQuestionId())) {
                        unfinshed.setAnswerOther(leanPaintReportTemp.getAnswerOther());
                        unfinshed.setAnswerId(leanPaintReportTemp.getAnswerId());
                        unfinshed.setAnswerPhoto(leanPaintReportTemp.getAnswerPhoto());
                        unfinshed.setStationReportUnFinshed(saveStationReportTemp);
                        stationLeanPaintReportTempRepository.save(unfinshed);
                    }
                    StationLeanPaintReportTemp paintReportTemp = stationLeanPaintReportTempRepository.selectAnswerByQuestion(reportId, leanPaintReportTemp.getQuestionId());
                    if (paintReportTemp == null) {
                        leanPaintReportTemp.setStationReportUnFinshed(saveStationReportTemp);
                        stationLeanPaintReportTempRepository.save(leanPaintReportTemp);
                    }
                }

            }
            logger.info("<<<<<<<<<<<<<<<<<<更新暂存报告成功>>>>>>>>>>>>>>>>>");
            stationReport = stationReportUnFinshedRepository.findOne(reportId);
            stationReport.setSectionId(sectionId);
            stationReport.setAnchor(anchor);
            stationReportUnFinshedRepository.save(stationReport);
            if (operationalDataAnalysisTempList != null) {
                logger.info("<<<<<<<<<<<<<<<<<<更新暂存表格数据>>>>>>>>>>>>>>>>>");
                QOperationalDataAnalysisTemp operationalDataAnalysisTemp = QOperationalDataAnalysisTemp.operationalDataAnalysisTemp;
                builder = new BooleanBuilder();
                builder.and(operationalDataAnalysisTemp.deleted.eq(false));
                builder.and(operationalDataAnalysisTemp.enabled.eq(true));
                builder.and(operationalDataAnalysisTemp.reportId.eq(reportId));
                builder.and(operationalDataAnalysisTemp.stationId.eq(stationId));
                List<OperationalDataAnalysisTemp> unfinishedOperationalDataAnalysisTempList = (List<OperationalDataAnalysisTemp>) operationalDataAnalysisTempRepository.findAll(builder);
                logger.info("<<<<<<<<<<<<<<<<<<逻辑删除原来暂存的表格数据>>>>>>>>>>>>>>>>>");
                for (OperationalDataAnalysisTemp unFinished : unfinishedOperationalDataAnalysisTempList) {
                    unFinished.setDeleted(true);
                    unFinished.setEnabled(false);
                    operationalDataAnalysisTempRepository.save(unFinished);
                }
                logger.info("<<<<<<<<<<<<<<<<<<新增暂存的表格数据>>>>>>>>>>>>>>>>>");
                for (OperationalDataAnalysisTemp operationalData : operationalDataAnalysisTempList) {
                    operationalData.setReportId(reportId);
                    operationalData.setStationId(stationId);
                    operationalDataAnalysisTempRepository.save(operationalData);
                }
            }
            logger.info("<<<<<<<<<<<<<<<<<<暂存完成>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<返回暂存的ID：" + reportId + ">>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponseWithData(reportId);
        }
    }


    @ApiOperation("判断维修站是否填写过基础报告-改")
    @RequestMapping(value = "judgeReport", method = RequestMethod.POST)
    public JsonResponse judgeReport(@ApiIgnore Principal principal,
                                    @ApiParam("维修站ID") @RequestParam(value = "stationId") String stationId,
                                    @ApiParam("是否是精益钣喷") @RequestParam(value = "type", required = false) String type) {
        logger.info("***************************************************************");
        logger.info("<<<<<<<<<<<<<<<<<<判断维修站是否填写过基础报告>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<维修站ID为：" + stationId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<是否是精益钣喷" + type + ">>>>>>>>>>>>>>>>>");
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        if (clientUser.getUserType().equals(UserType.customer)) {
            return JsonResponse.successResponse();
        }

        QStationReportTemp qStationReportTemp = QStationReportTemp.stationReportTemp;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qStationReportTemp.deleted.eq(false));
        booleanBuilder.and(qStationReportTemp.enabled.eq(true));
        booleanBuilder.and(qStationReportTemp.temporaryStationId.eq(Long.valueOf(stationId)));
        booleanBuilder.and(qStationReportTemp.user.id.eq(clientUser.getId()));
        List<StationReportTemp> stationReportTempList = (List<StationReportTemp>) stationReportUnFinshedRepository.findAll(booleanBuilder);
        if (stationReportTempList != null && stationReportTempList.size() >= 1) {
            return JsonResponse.errorResponseWithError("抱歉", "您已经暂存过此维修站信息，请去我的报告里查看");
        }

        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.station.id.eq(Long.valueOf(stationId)));
        builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
        List<StationReport> stationReportList = (List<StationReport>)stationReportRepository.findAll(builder);

        QAuditReport qAuditReport = QAuditReport.auditReport;
        builder = new BooleanBuilder();
        builder.and(qAuditReport.deleted.eq(false));
        builder.and(qAuditReport.enabled.eq(true));
        builder.and(qAuditReport.user.id.eq(clientUser.getId()));
        builder.and(qAuditReport.station.id.eq(Long.valueOf(stationId)));
        builder.and(qAuditReport.category.eq(Constants.TECHCOLOR_REPORT));
        List<AuditReport> auditReportList = (List<AuditReport>)auditReportRepository.findAll(builder);
        if (stationReportList == null  && stationReportList.size()>0
                && auditReportList == null && auditReportList.size()>0) {
            logger.info("<<<<<<<<<<<<<<<<<<此维修站是导入的维修站>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<需要补充数据>>>>>>>>>>>>>>>>>");
            AuditReport auditReport = new AuditReport();
            Station station = stationRepository.findOne(Long.valueOf(stationId));
            auditReport.setUser(clientUser);
            auditReport.setStation(station);
            auditReport.setAuditing(Constants.AUDIT_APPLY);
            auditReport.setCategory(Constants.TECHCOLOR_REPORT);
            auditReport.setSupplement(true);
            auditReportRepository.save(auditReport);
            AuditColorReport auditColorReport = new AuditColorReport();
            if (StringUtils.isNotEmpty(station.getProvince())) {
                auditColorReport.setAuditReport(auditReport);
                auditColorReport.setQuestionId(173L);
                auditColorReport.setAnswerOther(station.getProvince());
                auditColorReportRepository.save(auditColorReport);
            }
            auditColorReport = new AuditColorReport();
            if (StringUtils.isNotEmpty(station.getCity())) {
                auditColorReport.setAuditReport(auditReport);
                auditColorReport.setQuestionId(174L);
                auditColorReport.setAnswerOther(station.getCity());
                auditColorReportRepository.save(auditColorReport);
            }
            auditColorReport = new AuditColorReport();
            if (StringUtils.isNotEmpty(station.getName())) {
                auditColorReport.setAuditReport(auditReport);
                auditColorReport.setQuestionId(175L);
                auditColorReport.setAnswerOther(station.getName());
                auditColorReportRepository.save(auditColorReport);
            }
            auditColorReport = new AuditColorReport();
            if (StringUtils.isNotEmpty(station.getContact())) {
                auditColorReport.setAuditReport(auditReport);
                auditColorReport.setQuestionId(2L);
                auditColorReport.setAnswerOther(station.getContact());
                auditColorReportRepository.save(auditColorReport);
            }
            auditColorReport = new AuditColorReport();
            if (StringUtils.isNotEmpty(station.getStationNum())) {
                auditColorReport.setAuditReport(auditReport);
                auditColorReport.setQuestionId(181L);
                auditColorReport.setAnswerOther(station.getStationNum());
                auditColorReportRepository.save(auditColorReport);
            }
            logger.info("<<<<<<<<<<<<<<<<<<初始化维修站信息完毕>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<对应的基础报告ID为:" + auditReport.getId() + ">>>>>>>>>>>>>>>>>");
            return JsonResponse.errorResponseWithError("抱歉", "维修站信息不全，需补充信息", auditReport.getId());
        } else {
            if (auditReportList != null && auditReportList.size()>0) {
                if (auditReportList.get(0).getStation().isCheckStation() == false) {
                    logger.info("<<<<<<<<<<<<<<<<<<此维修站信息不全，需补充信息，基础报告ID为：" + auditReportList.get(0).getId() + ">>>>>>>>>>>>>>>>>");
                    return JsonResponse.errorResponseWithError("抱歉", "维修站信息不全，需补充信息", auditReportList.get(0).getId());
                }
                boolean isAuditTrue = false;
                qAuditReport = QAuditReport.auditReport;
                builder = new BooleanBuilder();
                builder.and(qAuditReport.deleted.eq(false));
                builder.and(qAuditReport.enabled.eq(true));
                builder.and(qAuditReport.station.id.eq(Long.valueOf(stationId)));
                builder.and(qAuditReport.category.eq(Constants.TECHCOLOR_REPORT));
                List<AuditReport> auditReportList1 = (List<AuditReport>) auditReportRepository.findAll(builder);
                for (AuditReport report : auditReportList1) {
                    if (report.getAuditing().equals(Constants.AUDIT_TRUE)) {
                        isAuditTrue = true;
                        break;
                    }
                }
                if (auditReportList.get(0).getAuditing().equals(Constants.AUDIT_APPLY) && !isAuditTrue) {
                    logger.info("<<<<<<<<<<<<<<<<<<维修站(基础报告)正在审核中/维修站信息不全，无法填写其他报告>>>>>>>>>>>>>>>>>");
                    return JsonResponse.errorResponseWithError("抱歉", "维修站(基础报告)正在审核中/维修站信息不全，无法填写其他报告");
                }
                if (auditReportList.get(0).getAuditing().equals(Constants.AUDIT_FALSE) && !isAuditTrue) {
                    logger.info("<<<<<<<<<<<<<<<<<<维修站(基础报告)审核未通过，无法填写其他报告>>>>>>>>>>>>>>>>>");
                    return JsonResponse.errorResponseWithError("抱歉", "维修站(基础报告)审核未通过，无法填写其他报告");
                }
            }
            if (StringUtils.isNotEmpty(type) && type.equals(Constants.PAINT_REPORT)) {
                qStationReport = QStationReport.stationReport;
                builder = new BooleanBuilder();
                builder.and(qStationReport.deleted.eq(false));
                builder.and(qStationReport.enabled.eq(true));
                builder.and(qStationReport.station.id.eq(Long.valueOf(stationId)));
                builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
                builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
                Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
                Pageable pageable = new PageRequest(0, 1, sort);
                List<StationReport> stationReportList1 = stationReportRepository.findAll(builder, pageable).getContent();
                if (stationReportList1 != null && stationReportList1.size() > 0) {
                    return JsonResponse.successResponseWithData(stationReportList1.get(0).getId());
                }
                return JsonResponse.successResponse();
            }
        }
        return JsonResponse.successResponse();
    }


    String getAnswerString(String answerIds) {
        List<String> answers = new ArrayList<>();
        List<Long> answerIdArray = ArrayStringUtil.getStringIds(answerIds);
        for (Long answerId : answerIdArray) {
            QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(answerId);
            answers.add(questionAnswerOption.getName());
        }
        return StringUtils.join(answers, ",");
    }

    String filterAnswerOther(String answerOther) {
        try {
            Long currentMin = Long.parseLong(answerOther);
            if (currentMin > 1000000) {
                Date date = new Date(currentMin);
                if (ValidateUtil.isValidMobileNo(answerOther)) {
                    return DateUtil.formatDate(date, Constants.DATE_FORMAT);
                } else {
                    return AnswerOtherUtil.getOtherString(answerOther);
                }
            } else {
                return AnswerOtherUtil.getOtherString(answerOther);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AnswerOtherUtil.getOtherString(answerOther);
        }
    }

    String filterAnswerId(String answerIds) {
        if (null == answerIds) {
            return "";
        } else {
            return answerIds;
        }
    }


}
